using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace Commons.Parser
{
	public abstract class BaseXmlParser<T> : IDisposable
	{
		protected TextReader textReader;

		public void LoadFromFileSystem(string path)
		{
			if (!File.Exists(path))
			{
				throw new Exception("File " + path + " not found");
			}

			textReader = File.OpenText(path);
		}

		protected T Deserialize()
		{
			if (textReader == null)
			{
				throw new Exception(GetType().Name + " must be loaded before deserialize");
			}

			using (XmlTextReader xmlReader = new XmlTextReader(textReader))
			{
				XmlSerializer serializer = new XmlSerializer(typeof(T));

				return (T) serializer.Deserialize(xmlReader);
			}
		}

		public void Dispose()
		{
			if (textReader != null)
			{
				textReader.Dispose();
				textReader = null;
			}
		}
	}
}

